import { useEffect, useState } from 'react'
import { Stencil } from '@antv/x6-plugin-stencil'
import './index.less'
import { nodeConfigByIcon } from '../flow-canvas/nodes'
import { NODE_TYPE_DRAG } from '@/utils/constant.js'

const SiderBar = ({ domId, treeData, graph }) => {
  const initStencil = () => {
    const stencil = new Stencil({
      title: '',
      target: graph,
      stencilGraphWidth: 288,
      stencilGraphHeight: Math.ceil(treeData.length / 3) * 64,
      stencilGraphPadding: 0,
      collapsable: false,
      groups: [
        {
          title: '常用',
          collapsed: true,
          name: 'group1',
        },
      ],
      layoutOptions: {
        dx: 0,
        dy: 0,
        columns: 3,
        columnWidth: 96,
        rowHeight: 64,
      },
    })

    document.getElementById(domId).appendChild(stencil.container)
    loadS(stencil)
  }

  const loadS = (stencil) => {
    const nodes = treeData.map((item) => {
      let node = graph.createNode(nodeConfigByIcon(item.template_name, item.template_icon))
      node.data = item
      node.data.nodeType = NODE_TYPE_DRAG
      return node
    })

    stencil.load(nodes, 'group1')
  }

  useEffect(() => {
    if (treeData.length > 0 && graph) {
      initStencil()
    }
  }, [graph, treeData])

  return (
    <>
      <div id={domId}></div>
    </>
  )
}

export default SiderBar
